<template>
	<view class="publish-page">
		<!-- 顶部标题区 -->
		<view class="page-header">
			<text class="page-title">{{ selectedPlate ? selectedPlate.plateName : '发布帖子' }}</text>
			<text class="page-subtitle">{{ selectedPlate ? selectedPlate.plateDesc : '分享你的想法和见解' }}</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-container">
			<up-form ref="formRef" :model="formData" :rules="rules" labelPosition="top">
				<!-- 话题分类 -->
				<view class="form-item">
					<view class="item-label">
						<text class="label-text">话题分类</text>
						<text class="label-required">*</text>
					</view>
					<view class="category-selector" @click="showSubCategoryPicker = true">
						<text class="category-text" v-if="formData.subCategory">{{ formData.subCategory }}</text>
						<text class="category-placeholder" v-else>请选择话题分类</text>
						<up-icon name="arrow-down" size="16" color="#999"></up-icon>
					</view>
				</view>

				<!-- 帖子标题 -->
				<view class="form-item">
					<view class="item-label">
						<text class="label-text">帖子标题</text>
						<text class="label-required">*</text>
					</view>
					<up-input 
						v-model="formData.title" 
						placeholder="请输入标题（5-100字）" 
						:maxlength="100"
						border="none"
						:clearable="true"
					/>
				</view>

				<!-- 帖子内容 -->
				<view class="form-item">
					<view class="item-label">
						<text class="label-text">帖子内容</text>
						<text class="label-required">*</text>
					</view>
					<up-textarea 
						v-model="formData.content" 
						placeholder="请输入内容，分享你的想法...（10-2000字）" 
						:maxlength="2000"
						count
						:autoHeight="true"
						:minHeight="300"
					/>
				</view>

				<!-- 图片上传 -->
				<view class="form-item">
					<view class="item-label">
						<text class="label-text">图片（选填）</text>
						<text class="label-hint">最多{{ maxImages }}张</text>
					</view>
					<view class="upload-area">
						<view class="image-list">
							<!-- 已上传的图片 -->
							<view class="image-item" v-for="(img, index) in formData.images" :key="index">
								<image :src="img" mode="aspectFill" class="uploaded-image"></image>
								<view class="image-delete" @click="handleDeleteImage(index)">
									<up-icon name="close-circle-fill" color="#fff" size="18"></up-icon>
								</view>
							</view>

							<!-- 上传按钮 -->
							<view class="upload-btn" @click="handleChooseImage" v-if="formData.images.length < maxImages">
								<up-icon name="camera" size="32" color="#999"></up-icon>
								<text class="upload-text">{{ formData.images.length }}/{{ maxImages }}</text>
							</view>
						</view>
					</view>
				</view>
			</up-form>

			<!-- 提交按钮 -->
			<view class="submit-container">
				<up-button 
					type="primary" 
					@click="handlePublish" 
					:loading="publishing"
					size="large"
					:customStyle="{
						background: 'linear-gradient(135deg, #667EEA 0%, #764BA2 100%)',
						border: 'none',
						fontSize: '32rpx',
						fontWeight: '600'
					}"
				>
					{{ publishing ? '发布中...' : '立即发布' }}
				</up-button>
			</view>
		</view>

		<!-- 子分类选择器 -->
		<up-picker 
			v-model:show="showSubCategoryPicker" 
			:columns="subCategoryColumns"
			@confirm="onSubCategoryConfirm"
			@cancel="showSubCategoryPicker = false"
		></up-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		mockPublishPost
	} from '../../server/mock.js';
	import showToast from '../../utils/showToast.js';
	import { addPostService } from '../../server/api/post.js';

	// 常量
	const maxImages = 9;

	// 状态
	const formRef = ref(null);
	const publishing = ref(false);
	const showSubCategoryPicker = ref(false);

	// 表单数据
	const formData = reactive({
		plateId: '',
		subCategory: '',
		title: '',
		content: '',
		images: []
	});

	// 子分类选项（根据plateId动态显示）
	const subCategoryColumns = computed(() => {
		const categories = {
			1: [['校园话题', '学习交流', '生活分享', '趣事杂谈', '其他']], // 讨论区
			2: [['生活好物', '学习资料', '美食分享', '摄影作品', '其他']]  // 分享区
		};
		return categories[formData.plateId] || [['其他']];
	});

	// 表单验证规则
	const rules = {
		subCategory: [{
			required: true,
			message: '请选择话题分类',
			trigger: ['blur', 'change']
		}],
		title: [{
				required: true,
				message: '请输入标题',
				trigger: ['blur', 'change']
			},
			{
				min: 5,
				max: 100,
				message: '标题长度在5-100字之间',
				trigger: ['blur', 'change']
			}
		],
		content: [{
				required: true,
				message: '请输入内容',
				trigger: ['blur', 'change']
			},
			{
				min: 10,
				max: 2000,
				message: '内容长度在10-2000字之间',
				trigger: ['blur', 'change']
			}
		]
	};

	// 计算选中的板块
	const selectedPlate = computed(() => {
		const plateMap = {
			1: { plateId: 1, plateName: '发布讨论', plateDesc: '分享观点，参与讨论' },
			2: { plateId: 2, plateName: '发布分享', plateDesc: '分享资料、好物、美图' }
		};
		return plateMap[formData.plateId] || { plateName: '发布帖子', plateDesc: '分享你的想法和见解' };
	});

	/**
	 * 子分类确认
	 */
	const onSubCategoryConfirm = ({ value }) => {
		formData.subCategory = value[0];
		showSubCategoryPicker.value = false;
	};

	/**
	 * 选择图片
	 */
	const handleChooseImage = () => {
		const remainCount = maxImages - formData.images.length;

		uni.chooseImage({
			count: remainCount,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;

				// 模拟上传（实际应该调用上传接口）
				tempFilePaths.forEach(path => {
					// 这里应该调用 mockUploadImage，但为了简化，直接使用临时路径
					formData.images.push(path);
				});

				showToast(`已选择${tempFilePaths.length}张图片`, 'success');
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
				showToast('选择图片失败', 'error');
			}
		});
	};

	/**
	 * 删除图片
	 */
	const handleDeleteImage = (index) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除这张图片吗？',
			success: (res) => {
				if (res.confirm) {
					formData.images.splice(index, 1);
				}
			}
		});
	};

	/**
	 * 发布帖子
	 */
	const handlePublish = async () => {
		console.log("test");
		
		// 检查登录状态
		const token = uni.getStorageSync('token');
		const userInfo = uni.getStorageSync('userInfo');

		if (!token || !userInfo) {
			showToast('请先登录', 'none');
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1000);
			return;
		}

		// 表单验证
		try {
			await formRef.value.validate();
		} catch (errors) {
			console.log('表单验证失败:', errors);
			return;
		}

		publishing.value = true;

		try {
			// 准备发布数据
			const publishData = {
				userId: userInfo.userId,
				plateId: formData.plateId,
				title: formData.title,
				content: formData.content,
				image: JSON.stringify(formData.images) // 图片数组
			};

			// 发布
			const res = await addPostService(publishData);
			console.log(res);

			if (res.code === 200) {
				showToast('发布成功', 'success');

				// 延迟返回
				setTimeout(() => {
					uni.navigateBack({
						delta: 1,
						success: () => {
							// 通知帖子列表页刷新（可以使用事件总线或全局状态管理）
							uni.$emit('refreshPosts');
						}
					});
				}, 1000);
			} else {
				showToast(res.message || '发布失败', 'error');
			}
		} catch (error) {
			console.error('发布异常:', error);
			showToast('网络错误，请稍后重试', 'error');
		} finally {
			publishing.value = false;
		}
	};

	/**
	 * 保存草稿
	 */
	const handleSaveDraft = () => {
		// 保存到本地存储
		uni.setStorageSync('postDraft', {
			...formData,
			saveTime: Date.now()
		});

		showToast('草稿已保存', 'success');
	};

	/**
	 * 恢复草稿
	 */
	const restoreDraft = () => {
		const draft = uni.getStorageSync('postDraft');

		if (draft) {
			uni.showModal({
				title: '提示',
				content: '检测到未发布的草稿，是否恢复？',
				success: (res) => {
					if (res.confirm) {
						Object.assign(formData, draft);
						showToast('草稿已恢复', 'success');
					}
				}
			});
		}
	};

	// 页面加载时
	// 页面加载时接收plateId参数
	onLoad((options) => {
		if (options.plateId) {
			formData.plateId = parseInt(options.plateId);
		}
	});

	// onMounted(() => {
	// 	// restoreDraft(); // 可选：恢复草稿
	// });

	// 页面卸载时保存草稿
	// onBeforeUnmount(() => {
	// 	if (formData.title || formData.content) {
	// 		handleSaveDraft();
	// 	}
	// });
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

.publish-page {
	min-height: 100vh;
	background: $bg-page;
	padding-bottom: 120rpx;

	.page-header {
		@include gradient-bg(135deg, $primary-color, $secondary-color);
		padding: $spacing-xxl;
		padding-top: 120rpx;
		text-align: center;
		color: #fff;
		position: relative;

		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			background: linear-gradient(to bottom, transparent, $bg-page);
			pointer-events: none;
		}

		.page-title {
			display: block;
			font-size: $font-xxl;
			font-weight: $font-bold;
			margin-bottom: $spacing-sm;
		}

		.page-subtitle {
			display: block;
			font-size: $font-sm;
			opacity: 0.9;
		}
	}

	.form-container {
		margin-top: -60rpx;
		padding: 0 $spacing-base;

		.form-item {
			@include card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;

			.item-label {
				@include flex-between;
				margin-bottom: $spacing-base;

				.label-text {
					font-size: $font-base;
					color: $text-primary;
					font-weight: $font-semibold;
				}

				.label-required {
					color: $error-color;
					margin-left: $spacing-xs;
				}

				.label-hint {
					font-size: $font-sm;
					color: $text-tertiary;
				}
			}

			// 分类选择器
			.category-selector {
				@include flex-between;
				padding: $spacing-base;
				background: $bg-page;
				border-radius: $radius-base;
				border: 1px solid $border-light;
				transition: all $transition-fast;

				&:active {
					background: $bg-hover;
					border-color: $primary-color;
				}

				.category-text {
					font-size: $font-base;
					color: $text-primary;
					font-weight: $font-medium;
				}

				.category-placeholder {
					font-size: $font-base;
					color: $text-tertiary;
				}
			}

			// 图片上传区域
			.upload-area {
				.image-list {
					display: flex;
					flex-wrap: wrap;
					gap: $spacing-base;

					.image-item {
						position: relative;
						width: 200rpx;
						height: 200rpx;
						border-radius: $radius-md;
						overflow: hidden;

						.uploaded-image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}

						.image-delete {
							position: absolute;
							top: $spacing-xs;
							right: $spacing-xs;
							width: 40rpx;
							height: 40rpx;
							@include flex-center;
							background: rgba(0, 0, 0, 0.5);
							border-radius: $radius-round;
							backdrop-filter: blur(4px);
						}
					}

					.upload-btn {
						width: 200rpx;
						height: 200rpx;
						@include flex-center;
						flex-direction: column;
						gap: $spacing-xs;
						background: $bg-page;
						border: 2rpx dashed $border-base;
						border-radius: $radius-md;
						transition: all $transition-fast;

						&:active {
							background: $bg-hover;
							border-color: $primary-color;
						}

						.upload-text {
							font-size: $font-xs;
							color: $text-tertiary;
						}
					}
				}
			}
		}

		.submit-container {
			margin-top: $spacing-xxl;
		}
	}
}
</style>

